
import 'package:sqflite/sqflite.dart';
import 'package:umeng_push_demo/model/push_message_model.dart';
import 'package:umeng_push_demo/model/sqlite_manager.dart';

/// FileName push_message_dao
///
/// @Author 陈晓星
/// @Date 2024/10/28 13:12
///
/// @Description TODO

class PushMessageDao {
  /// 新增
  static Future<bool> insert(PushMessageModel model) async {
    if (!SqliteManager.shared.isEnable) return false;

    try {
      // String sql = 'insert into push_message(deviceToken,tag,alias,content,dateTime) values (?,?,?,?,?)';
      // await SqliteManager.shared.database!.execute(
      //   sql,
      //   [model.deviceToken, model.tag, model.alias, model.content, model.dateTime],
      // );
      await SqliteManager.shared.database!.insert(
          "push_message",
          {
            "type": model.type.value,
            "deviceToken": model.deviceToken,
            "tag": model.tag,
            "alias": model.alias,
            "content": model.content,
            "dateTime": model.dateTime
          },
          conflictAlgorithm: ConflictAlgorithm.replace
      );
      return true;
    } catch (e) {
      print('新增消息错误: $e');
      return false;
    }
  }

  /// 查找所有
  static Future<List<PushMessageModel>?> queryAll() async {
    if (!SqliteManager.shared.isEnable) return null;

    List<PushMessageModel> result = [];
    try {
      String sql = 'select * from push_message order by id desc';
      List list = await SqliteManager.shared.database!.rawQuery(sql);
      for (final item in list) {
        PushMessageModel m = PushMessageModel.fromDB(item);
        result.add(m);
      }
    } catch (e) {
      print('查找所有错误: $e');
    }
    return result;
  }

  /// 删除所有
  static Future<bool> deleteAll() async {
    if (!SqliteManager.shared.isEnable) return false;

    try {
      String sql = 'delete from push_message';
      await SqliteManager.shared.database!.execute(sql);
      return true;
    } catch (e) {
      print('删除所有错误: $e');
      return false;
    }
  }
}